import re

def parse(code):
    # split tokens
    code = re.sub("(\#?\()", lambda m: ' %s ' % m.group(1), code)
    code = code.replace(')', ' ) ')
    tokens = code.split()

    def parenthesis_stack(qt):
        def parent_stack(s):
            return s.count('(') - s.count(')')
        return sum(map(parent_stack, qt))

    # join quotes & strings
    new_tokens = []
    regular, quote_simple, string = 1, 2, 3
    parsing = regular
    temp = []
    for tk in tokens:
        if parsing == regular:
            if tk == "'" or tk == '#(':
                parsing = quote_simple
                temp = [tk]
            elif tk.startswith('"') and not tk.endswith('"'):
                parsing = string
                temp = [tk]
            else:
                new_tokens.append(tk)
        elif parsing == quote_simple:
            temp.append(tk)
            if parenthesis_stack(temp) == 0:
                parsing = regular
                new_tokens.append(''.join(temp[0:2]) + ' '.join(temp[2:]))
        elif parsing == string:
            temp.append(tk)
            if tk.endswith('"') and not tk.endswith('\\"'):
                parsing = regular
                new_tokens.append(' '.join(temp))

    return new_tokens

code = """
(equal? "abc" "abc")

"""

print parse(code)
